<script lang="ts" setup>
import { reactive, toRaw, ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Form } from 'ant-design-vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { postSysUserApi, getSysUserIdApi, putSysUserIdApi } from '@/common/apis/information'
import { getLeaderListApi } from '@/common/apis/organization'
import { getLeadertreeData1 } from '@/common/utils/backg-tree'
import { useRoute } from 'vue-router'


const useForm = Form.useForm;

// 获取传递过来的id
const route = useRoute()

// 获取路由参数id
const employeeId = route.params.id

const labelCol = { span: 4 };
const wrapperCol = { span: 14 };
const loading = ref<boolean>(false);
const departmentId1 = ref<string[]>()
const router = useRouter();

// 员工数据
const modelRef = reactive({
    username: '',  // 员工名字
    mobile: '', //  员工手机号
    formOfEmployment: '', // 员工聘用形式
    workNumber: '', // 员工工号
    departmentId: [], // 用于存储选中的部门路径 // 员工部门id
    timeOfEntry: '', // 员工入职日期
    correctionTime: '', // 员工转正日期
    staffPhoto: '', // 头像信息
});


// 类型校验
const rulesRef = reactive({
    username: [
        {
            required: true,
            message: '姓名不能为空',
        },
        { min: 2, max: 4, message: '姓名2-4个字符', trigger: 'blur' }
    ],
    mobile: [
        { required: true, message: '请输入手机号码', trigger: 'change' },
        {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码必须以1开头,并且满11位的号码',
            trigger: 'blur',
        },
    ],
    formOfEmployment: [
        {
            required: true,
            message: '请选择聘用形式',
        },
    ],
    departmentId: [
        {
            required: true,
            message: '请选择部门',
        },
    ],
    timeOfEntry: [
        {
            required: true,
            message: '请选择入职时间',
        },
    ],
    correctionTime: [
        {
            required: true,
            message: '请选择转正时间',
        },
        // 新增自定义校验规则
        {
            validator: (rule: null, value: string, callback: (error?: string) => void) => {
                // 当两个时间都已填写时进行校验
                if (value && modelRef.timeOfEntry) {
                    // 直接比较字符串 (格式为YYYY-MM-DD)
                    if (value < modelRef.timeOfEntry) {
                        return callback('转正时间不能早于入职时间！');
                    }
                }
                callback(); // 校验通过
            }
        }
    ],

});

// 获取部门列表数据
const departmentIdData = async () => {
    const res = await getLeaderListApi()
    const data = res.data.data

    // 转成树形结构
    departmentId1.value = getLeadertreeData1(data)

}

const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef, {
    onValidate: (...args) => console.log(...args),
});

// 获取员工基本信息
const getSysUserIdData = async () => {
    const res = await getSysUserIdApi({ id: employeeId });
    const employeeData = res.data.data; // 假设接口返回的数据在 res.data 中

    // 使用 Object.assign 更新 modelRef
    Object.assign(modelRef, employeeData);
}

// 点击保存
const onSubmit = async () => {
    validate()
        .then(async () => {
            // 提取最后一个 value 得出哪个部门
            const selectedDepartmentId = modelRef.departmentId[modelRef.departmentId.length - 1];

            // 判断是否传递id 新增 修改
            if (employeeId) {
                const submitData = {
                    ...toRaw(modelRef), // 展开其他表单数据
                    departmentId: selectedDepartmentId, // 替换 departmentId 为选中的最后一个 value
                };

                await putSysUserIdApi(submitData)
                message.success('修改员工数据成功')
            } else {
                // 构造提交的数据对象
                const submitData = {
                    ...toRaw(modelRef), // 展开其他表单数据
                    departmentId: selectedDepartmentId, // 替换 departmentId 为选中的最后一个 value
                };

                // 调用接口提交数据
                await postSysUserApi(submitData);
                message.success('提交成功')
            }
            router.push('/information')
        })
        .catch(err => {
            console.log('error', err);
        });
};

onMounted(() => {
    departmentIdData()
    getSysUserIdData()
})

</script>

<template>
    <div class="employee">
        <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
            <!-- 姓名 -->
            <a-form-item label="姓名" v-bind="validateInfos.username">
                <a-input v-model:value="modelRef.username" placeholder="请输入姓名" />
            </a-form-item>
            <!-- 工号 -->
            <a-form-item label="工号" v-bind="validateInfos.workNumber">
                <a-input disabled v-model="modelRef.workNumber" />
            </a-form-item>
            <!-- 手机号码 -->
            <a-form-item label="手机" v-bind="validateInfos.mobile">
                <a-input v-model:value="modelRef.mobile" placeholder="请输入手机号码" />
            </a-form-item>
            <!-- 部门 -->
            <a-form-item label="部门" v-bind="validateInfos.departmentId">
                <a-cascader v-model:value="modelRef.departmentId" :options="departmentId1" expand-trigger="hover"
                    placeholder="选择部门" />
            </a-form-item>
            <!-- 聘用形式 -->
            <a-form-item label="聘用形式" v-bind="validateInfos.formOfEmployment">
                <a-select v-model:value="modelRef.formOfEmployment" placeholder="聘用形式">
                    <a-select-option :value="1">正式</a-select-option>
                    <a-select-option :value="0">非正式</a-select-option>
                </a-select>
            </a-form-item>
            <!-- 入职时间 -->
            <a-form-item label="入职时间" v-bind="validateInfos.timeOfEntry">
                <a-date-picker v-model:value="modelRef.timeOfEntry" value-format="YYYY-MM-DD" />
            </a-form-item>
            <!-- 转正时间 -->
            <a-form-item label="转正时间" v-bind="validateInfos.correctionTime">
                <a-date-picker v-model:value="modelRef.correctionTime" value-format="YYYY-MM-DD" />
            </a-form-item>
            <!-- 头像上传 -->
            <a-form-item label="头像上传" v-bind="validateInfos.staffPhoto">
                <a-upload v-model:value="modelRef.staffPhoto" name="avatar" list-type="picture-card"
                    class="avatar-uploader" :show-upload-list="false">
                    <a-image :preview="false" v-if="modelRef.staffPhoto" :src="modelRef.staffPhoto" alt="avatar" />
                    <div v-else>
                        <LoadingOutlined v-if="loading"></LoadingOutlined>
                        <PlusOutlined v-else></PlusOutlined>
                        <div class="ant-upload-text">Upload</div>
                    </div>
                </a-upload>
            </a-form-item>

            <!-- 保存按钮 -->
            <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
                <a-button style="margin-left: 10px" @click="resetFields">取消</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>

<style lang="scss" scoped>
.employee {
    background-color: rgb(255, 255, 255);
    padding: 40px;
}

.avatar-uploader>.ant-upload {
    width: 128px;
    height: 128px;
}

.ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
}
</style>